import { isHasChinese } from '@/utils/index'

/**
 * 获取符合请求格式的消息列表
 * @return
 */
export function getMessageList (rootNode) {
  const list = []
  let cur = rootNode
  while (cur) {
    // 如果服务前返回的节点是错误信息，则跳过
    if (cur.next?.status === 'error' || cur.next?.target?.content === '') {
      cur = cur.next?.next
      continue
    }
    const listRole = ['assistant', 'user']
    if (listRole.includes(cur.role)) {
      list.push({
        role: cur.role,
        content: cur.target?.content || '',
        message_id: cur.message_id,
        parent_message_id: cur.parent_message_id,
        message_type: '',
        prompt_menu_icon: cur.target?.prompt_menu_icon,
        prompt_menu_title: cur.target?.prompt_menu_title,
        prefix: cur.target?.prefix,
        business: cur.target?.business
      })
    }
    cur = cur.next
  }
  return list
}

export function getResendMessageList (rootNode, curNode) {
  const list = getMessageList(rootNode)
  const cur = getPrevValidateCode(curNode, 'user')
  if (cur) {
    list.push({
      role: cur.role,
      content: cur.target?.content || '',
      message_id: cur.message_id,
      parent_message_id: cur.parent_message_id,
      message_type: '',
      prompt_menu_icon: cur.target?.prompt_menu_icon,
      prompt_menu_title: cur.target?.prompt_menu_title,
      prefix: cur.target?.prefix,
      business: cur.target?.business
    })
  }
  return list
}

/**
 * // 获取前一次有效的会话id，因为渲染节点有多种，user/asitant/tips ,  其中只有user/assitant为有效节点，其他为展示节点
 * @param node 当前节点
 * @returns
 */
export function getPrevValidateCode (node, role) {
  let cur = node
  while (cur) {
    if (cur.role === role && cur.status !== 'error' && cur.target?.content !== '') return cur
    cur = cur.prev
  }
  return null
}

// 获取chat接口请求发送需要的参数
export function getSendParams (
  messages,
  model,
  conversionId,
  knowledge_id
) {
  return {
    model: model.model,
    conversation_id: conversionId,
    stream: true,
    knowledge_id,
    add_llm_thought: true,
    messages: messages.concat(),
    role: 'user'
  }
}

export function combnePrompMenuWithMessage (
  message,
  promptMenu
) {
  if (!promptMenu) return message
  const item = {
    ...message,
    prompt_menu_icon: promptMenu.icon,
    prompt_menu_title: promptMenu.title,
    prefix: promptMenu.prefix
  }
  if (promptMenu.title === '翻译') {
    item.prefix = promptMenu.prefix.replace(
      '{lang}',
      isHasChinese(message.content) ? '英文' : '中文'
    )
  }
  return item
}
